// create namespace for plugins
Ext.namespace('Ext.ux.plugins');
 
/**
 * Ext.ux.plugins.textareaLength plugin for Ext.form.fieldbox
 *
 * @author  Charlie
 * @date    January 7, 2008
 *
 * @class Ext.ux.plugins.textareaLength
 * @extends Ext.util.Observable
 */
Ext.ux.plugins.textareaLength = function(config) {
    Ext.apply(this, config);
};
 
// plugin code
Ext.extend(Ext.ux.plugins.textareaLength, Ext.util.Observable, {
    init:function(field) {
		var thisXType = field.getXType();
		if (false == (field instanceof Ext.form.TextArea)) 
			return; // I only want to modify textarea fields.
		var maxChars = field.maxLength;
		var charsLeft;
		var prefix = '可输入字符数 剩余 ';
		var suffix = ' of ' + maxChars ;
		var instanceId = field.id + '-charsLeft';

		var getCharsLeft = function(field) {
			var charsLeft = maxChars - field.getValue().length;
			return charsLeft;
		};

		var keyupHandler = function(f, evt) {
			charsLeft = getCharsLeft(f);
			if(charsLeft < 0){
					Ext.MessageBox.alert("错误","超过最大字符数");
					field.setValue(field.getValue().substring(0,maxChars));
					charsLeft = getCharsLeft(f);
			}
			Ext.getDom(instanceId).innerHTML = prefix + charsLeft + suffix;
		};	
		
        Ext.apply(field, {
            enableKeyEvents: true,
			onRender: field.onRender.createSequence(function(ct, position) {
				if (Ext.getDom(instanceId)) return;
					charsLeft = getCharsLeft(field);
				var reminder = {
					tag: 'div',
					id: instanceId,
					html: prefix + charsLeft + suffix,
					style: 'padding:1px 1px 5px 1px; color:#FF0000; '
				}
				Ext.DomHelper.insertAfter(this.el, reminder);
				field.on('keyup', keyupHandler);
			}),
			
			onDestroy: field.onDestroy.createSequence(function() {
				var el = Ext.getDom(instanceId);
				if (el) {
					Ext.removeNode(el);
				}
			})
        });
		
		
    } // end of function init
}); // end of extend
 
// end of file